package com.xujie.sportsmeeting.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xujie.sportsmeeting.common.result.Result;
import com.xujie.sportsmeeting.dto.RegistrationDTO;
import com.xujie.sportsmeeting.dto.RegistrationQueryDTO;
import com.xujie.sportsmeeting.service.RegistrationService;
import com.xujie.sportsmeeting.vo.RegistrationVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 报名管理控制器
 */
@Tag(name = "报名管理", description = "报名管理相关接口")
@RestController
@RequestMapping("/registration")
@RequiredArgsConstructor
public class RegistrationController {

    private final RegistrationService registrationService;

    @Operation(summary = "获取报名列表")
    @GetMapping("/list")
    public Result<IPage<RegistrationVO>> getRegistrationList(RegistrationQueryDTO queryDTO, Authentication authentication) {
        IPage<RegistrationVO> page = registrationService.getRegistrationPage(queryDTO, authentication);
        return Result.success(page);
    }

    @Operation(summary = "获取报名详情")
    @GetMapping("/{id}")
    public Result<RegistrationVO> getRegistrationDetail(@PathVariable Long id) {
        RegistrationVO registrationDetail = registrationService.getRegistrationDetail(id);
        if (registrationDetail == null) {
            return Result.error("报名信息不存在");
        }
        return Result.success(registrationDetail);
    }

    @Operation(summary = "创建报名")
    @PostMapping
    public Result<Void> createRegistration(@Valid @RequestBody RegistrationDTO registrationDTO) {
        try {
            boolean success = registrationService.createRegistration(registrationDTO);
            if (success) {
                return Result.success("报名成功");
            } else {
                return Result.error("报名失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "更新报名信息")
    @PutMapping("/{id}")
    public Result<Void> updateRegistration(@PathVariable Long id, @Valid @RequestBody RegistrationDTO registrationDTO) {
        try {
            boolean success = registrationService.updateRegistration(id, registrationDTO);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "删除报名")
    @DeleteMapping("/{id}")
    public Result<Void> deleteRegistration(@PathVariable Long id) {
        boolean success = registrationService.removeById(id);
        if (success) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    @Operation(summary = "批量删除报名")
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteRegistrations(@RequestBody List<Long> ids) {
        boolean success = registrationService.removeByIds(ids);
        if (success) {
            return Result.success("批量删除成功");
        } else {
            return Result.error("批量删除失败");
        }
    }

    @Operation(summary = "审核报名")
    @PostMapping("/{id}/review")
    public Result<Void> reviewRegistration(@PathVariable Long id, @RequestBody ReviewRequest request, Authentication authentication) {
        try {
            // 获取当前用户ID（这里简化处理，实际应该从用户信息中获取）
            Long reviewerId = 1L; // 临时处理，实际应该从authentication中获取用户ID
            
            boolean success = registrationService.reviewRegistration(id, request.getStatus(), request.getReviewRemark(), reviewerId);
            if (success) {
                String action = request.getStatus() == 1 ? "审核通过" : "审核拒绝";
                return Result.success(action + "成功");
            } else {
                return Result.error("审核失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "取消报名")
    @PostMapping("/{id}/cancel")
    public Result<Void> cancelRegistration(@PathVariable Long id) {
        try {
            boolean success = registrationService.cancelRegistration(id);
            if (success) {
                return Result.success("取消报名成功");
            } else {
                return Result.error("取消报名失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "分配参赛号码")
    @PostMapping("/{id}/race-number")
    public Result<Void> assignRaceNumber(@PathVariable Long id, @RequestBody RaceNumberRequest request) {
        try {
            boolean success = registrationService.assignRaceNumber(id, request.getRaceNumber());
            if (success) {
                return Result.success("分配参赛号码成功");
            } else {
                return Result.error("分配参赛号码失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "根据运动员ID获取报名信息")
    @GetMapping("/athlete/{athleteId}")
    public Result<List<RegistrationVO>> getRegistrationsByAthleteId(@PathVariable Long athleteId) {
        List<RegistrationVO> registrations = registrationService.getRegistrationsByAthleteId(athleteId);
        return Result.success(registrations);
    }

    @Operation(summary = "根据项目ID获取已通过审核的报名信息")
    @GetMapping("/event/{eventId}/approved")
    public Result<List<RegistrationVO>> getApprovedRegistrationsByEventId(@PathVariable Long eventId) {
        List<RegistrationVO> registrations = registrationService.getApprovedRegistrationsByEventId(eventId);
        return Result.success(registrations);
    }

    @Operation(summary = "检查是否已报名")
    @GetMapping("/check")
    public Result<Boolean> checkRegistration(@RequestParam Long athleteId, @RequestParam Long eventId) {
        boolean isRegistered = registrationService.isAlreadyRegistered(athleteId, eventId);
        return Result.success(isRegistered);
    }

    // 内部请求类
    public static class ReviewRequest {
        private Integer status;
        private String reviewRemark;
        
        public Integer getStatus() {
            return status;
        }
        
        public void setStatus(Integer status) {
            this.status = status;
        }
        
        public String getReviewRemark() {
            return reviewRemark;
        }
        
        public void setReviewRemark(String reviewRemark) {
            this.reviewRemark = reviewRemark;
        }
    }

    public static class RaceNumberRequest {
        private String raceNumber;
        
        public String getRaceNumber() {
            return raceNumber;
        }
        
        public void setRaceNumber(String raceNumber) {
            this.raceNumber = raceNumber;
        }
    }
}
